// pages/release-recruitment/release-recruitment.js
import { Job } from '../../models/job'
import { Company } from '../../models/company'
import UploadImg from '../../util/uploadImg'
import { check } from '../../util/identityCheck'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'
const jobModel = new Job()
const companyModel = new Company()
const uploadImg = new UploadImg()
import areaList from '../../util/area'

import { Publish } from '../../models/other'
const publishModel = new Publish()

import { RedPacket } from '../../models/redpacket'

let packetModel = new RedPacket()

function getShareId() {
  const shareId = wx.getStorageSync('otherId')
  if (shareId && shareId != 'undefined') {
    // 注意 这里是字符串类型的undefined 好奇我为什么没封装一下？因为我真的很忙
    return shareId
  } else {
    return ''
  }
}
Page({
  data: {
    id: null,
    areaList,
    PubEmployment: {
      shareUserId: '',
      title: '',
      recruitStation: '',
      recruitSex: '',
      recruitAge: '',
      jobExperience: '',
      salary: '',
      shopType: '',
      shopName: '',
      jobDescription: '',
      recruitNumber: '',
      shopArea: '',
      shopAddress: '',
      location: '',
      contactName: '',
      contactPhone: '',
      socialBenefits: '',
      socialBenefitList: [],
      avatar: '',
      shopEnvironment: '',
      shopEnvironmentList: []
    },
    showPopup: {
      station: false,
      number: false,
      age: false,
      experience: false,
      salary: false,
      shopType: false,
      welfare: false,
      location: false
    },
    ageList: [],
    experienceList: [],
    salaryList: [],
    shopTypeList: [],
    welfareList: [],
    showRedPacketDialog: false,
    totalMoney: 0
  },

  chooseImage() {
    uploadImg.chooseImg(5, (res) => {
      let imgList = this.data.PubEmployment.shopEnvironmentList
      imgList.push(res)
      this.setData({
        'PubEmployment.shopEnvironmentList': imgList,
        'PubEmployment.shopEnvironment': imgList.join(',')
      })
    })
  },

  chooseLocation() {
    let that = this
    wx.chooseLocation({
      success(res) {
        console.log(res)
        that.setData({
          'PubEmployment.shopAddress': res.name
        })
      }
    })
  },

  publish() {
    let PubEmployment = this.data.PubEmployment
    if (!PubEmployment.avatar) {
      wx.showToast({
        title: '请上传封面图片',
        icon: 'none'
      })
      return
    }
    if (!PubEmployment.title) {
      wx.showToast({
        title: '请填写发布标题',
        icon: 'none'
      })
      return
    }
    if (!PubEmployment.recruitStation) {
      wx.showToast({
        title: '请选择岗位',
        icon: 'none'
      })
      return
    }
    if (!PubEmployment.recruitNumber) {
      wx.showToast({
        title: '请填写招聘人数',
        icon: 'none'
      })
      return
    }
    if (!PubEmployment.recruitSex) {
      wx.showToast({
        title: '请选择性别要求',
        icon: 'none'
      })
      return
    }
    if (!PubEmployment.recruitAge) {
      wx.showToast({
        title: '请选择年龄范围',
        icon: 'none'
      })
      return
    }
    if (!PubEmployment.jobExperience) {
      wx.showToast({
        title: '请选择经验要求',
        icon: 'none'
      })
      return
    }
    if (!PubEmployment.socialBenefits) {
      wx.showToast({
        title: '请选择福利待遇',
        icon: 'none'
      })
      return
    }
    if (!PubEmployment.salary) {
      wx.showToast({
        title: '请选择薪资范围',
        icon: 'none'
      })
      return
    }
    if (!PubEmployment.jobDescription) {
      wx.showToast({
        title: '请填写招聘具体要求',
        icon: 'none'
      })
      return
    }
    if (!PubEmployment.shopType) {
      wx.showToast({
        title: '请选择店铺类型',
        icon: 'none'
      })
      return
    }
    if (!PubEmployment.shopArea) {
      wx.showToast({
        title: '请填写店铺面积',
        icon: 'none'
      })
      return
    }
    if (!PubEmployment.location) {
      wx.showToast({
        title: '请选择所在区域',
        icon: 'none'
      })
      return
    }
    if (!PubEmployment.shopAddress) {
      wx.showToast({
        title: '请填写详细地址',
        icon: 'none'
      })
      return
    }
    if (!PubEmployment.contactName) {
      wx.showToast({
        title: '请填写联系人',
        icon: 'none'
      })
      return
    }
    if (/^[0-9]*$/.test(PubEmployment.contactName)) {
      wx.showToast({
        title: '联系人不可以是数字',
        icon: 'none'
      })
      return
    }
    if (!PubEmployment.contactPhone) {
      wx.showToast({
        title: '请填写联系电话',
        icon: 'none'
      })
      return
    }
    if (PubEmployment.contactPhone.includes('*')) {
      delete PubEmployment.contactPhone
    }
    this.removeDraft()
    jobModel.recruitPublish(PubEmployment, (res) => {})
    wx.navigateTo({
      url: `/pages/pay-join/pay-join?type=招聘&data=${JSON.stringify(
        PubEmployment
      )}`
    })
  },

  update() {
    let PubEmployment = this.data.PubEmployment
    Dialog.confirm({
      message: '更新后需再次审核\n 是否确认更新？'
    }).then(() => {
      if (PubEmployment.contactPhone.includes('*')) {
        delete PubEmployment.contactPhone
      }
      jobModel.recruitUpdate(PubEmployment, (res) => {
        Dialog.alert({
          title: '更新成功！',
          message: '平台将在24小时内完成审核，请耐心等待！'
        }).then(() => {
          wx.requestSubscribeMessage({
            tmplIds: [
              '-DHKrW9DRvbg3sEoVRYtcRxRyr-kYzyTN-9BNCY89rI',
              'b7FIjt52cUMvTClpMJKJLe8lzi4rnQsWlUc7D5VYGoA',
              'PbmE0p7hgtUXlZcUEgR_qBcP3tMhbe1-_wKNw7CkoZY'
            ],
            complete(res) {
              wx.navigateBack()
            }
          })
        })
      })
    })
  },

  getDetail() {
    jobModel.detail(
      {
        id: this.data.id
      },
      (res) => {
        this.setData({
          PubEmployment: { shopEnvironmentList: [], ...res }
        })
        if (res.auditStatus == 2) {
          Dialog.alert({
            title: '审核未通过',
            message: `未通过原因：${res.remark} \n 请重新修改并提交审核。`
          }).then(() => {
            // on close
          })
        }
        if (res.auditStatus == 3) {
          Dialog.alert({
            message: `下架原因：${res.remark} \n 如需继续使用请重新付费发布！`
          }).then(() => {
            // on close
          })
        }
      }
    )
  },

  onReady() {
    this.init()
  },

  uploadCover() {
    uploadImg.chooseImg(1, (imgUrl) => {
      this.setData({
        'PubEmployment.avatar': imgUrl
      })
    })
  },

  inputChange(evevt) {
    let key = `PubEmployment.${evevt.currentTarget.dataset.type}`
    this.setData({
      [key]: evevt.detail
    })
  },

  onTabChange(event) {
    console.log(event)
  },

  showDialog() {
    this.setData({
      isShowDialog: true
    })
  },

  showDialogTip() {
    this.setData({
      isShowDialogTip: true
    })
  },

  confirmDialogTip() {
    wx.navigateBack({
      delta: 1
    })
  },

  confirmDialog(event) {
    wx.navigateTo({
      url: '/pages/corporate-certification-detail/corporate-certification-detail'
    })
  },

  toNewPage(event) {
    let path = event.currentTarget.dataset.path
    let text = event.currentTarget.dataset.text
    wx.navigateTo({
      url: `/packageA/pages/${path}/${path}?text=${text}`
    })
  },

  closeRedDialog() {
    this.setData({
      showRedPacketDialog: false
    })
  },

  getPacketSize() {
    packetModel.getPacketSize((res) => {
      res.forEach((item) => {
        if (item.modeName == '招聘') {
          this.setData({
            totalMoney: item.totalMoney
          })
        }
      })
    })
  },

  onShow() {
    const shareUserId = getShareId()
    setTimeout(() => {
      this.setData({
        'PubEmployment.shareUserId': shareUserId
      })
    }, 1000)
    if (!check()) return
  },

  onLoad(options) {
    this.setData({
      id: options.id
    })
    if (+options.id) {
      this.getDetail()
    } else {
      this.getDraft()
      this.setData({
        showRedPacketDialog: true
      })
    }
  },

  onShowPopup(e) {
    // 打开弹窗
    wx.hideKeyboard()
    const which = e.currentTarget.dataset.key
    const key = `showPopup.${which}`
    this.setData({
      [key]: true
    })
  },

  onClosePopup(e) {
    // 关闭弹窗
    for (let key in this.data.showPopup) {
      key = `showPopup.${key}`
      this.setData({
        [key]: false
      })
    }
  },

  onStation(e) {
    //  岗位组件选中
    this.setData({
      'PubEmployment.recruitStation': e.detail
    })
  },

  onSex(e) {
    // 选择性别
    const sex = e.currentTarget.dataset.sex
    console.log(sex)
    this.setData({
      'PubEmployment.recruitSex': sex
    })
  },

  onAge(e) {
    // 选择性别
    const age = e.currentTarget.dataset.age
    this.setData({
      'PubEmployment.recruitAge': age
    })
  },

  onExperience(e) {
    // 选择工作经验
    const experience = e.currentTarget.dataset.experience
    this.setData({
      'PubEmployment.jobExperience': experience
    })
  },

  onSalary(e) {
    // 选择薪资范围
    const salary = e.currentTarget.dataset.salary
    this.setData({
      'PubEmployment.salary': salary
    })
  },

  onShopType(e) {
    // 选择薪资范围
    this.setData({
      'PubEmployment.shopType': e.detail
    })
  },

  onWelfare(e) {
    // 选择福利待遇
    this.setData({
      'PubEmployment.socialBenefits': e.detail
    })
  },

  onAreaConfirm(e) {
    const location = e.detail.values
    this.setData({
      'PubEmployment.location':
        location[0].name + location[1].name + location[2].name,
      'showPopup.location': false
    })
  },

  onAreaCancel(e) {
    this.setData({
      'showPopup.location': false
    })
  },

  getAgeList() {
    // 获取年龄要求范围
    publishModel.getPublicTypes(
      {
        tagKey: '年龄要求',
        type: 0
      },
      (res) => {
        this.setData({
          ageList: res
        })
      }
    )
  },

  getExperienceList() {
    // 获取工作经验范围
    publishModel.getPublicTypes(
      {
        tagKey: '工作经验',
        type: 0
      },
      (res) => {
        this.setData({
          experienceList: res
        })
      }
    )
  },
  getSalaryList() {
    // 获取薪资范围
    publishModel.getPublicTypes(
      {
        tagKey: '薪资范围',
        type: 0
      },
      (res) => {
        this.setData({
          salaryList: res
        })
      }
    )
  },
  getShopTypeList() {
    // 获取薪资范围
    publishModel.getPublicTypes(
      {
        tagKey: '店铺类型',
        type: 0
      },
      (res) => {
        this.setData({
          shopTypeList: res
        })
      }
    )
  },
  getWelfareList() {
    // 获取福利待遇
    publishModel.getPublicTypes(
      {
        tagKey: '福利待遇',
        type: 0
      },
      (res) => {
        this.setData({
          welfareList: res
        })
      }
    )
  },

  removeImg(e) {
    const index = e.currentTarget.dataset.index
    let imgList = this.data.PubEmployment.shopEnvironmentList
    imgList.splice(index, 1)
    this.setData({
      'PubEmployment.shopEnvironmentList': imgList,
      'PubEmployment.shopEnvironment': imgList.join(',')
    })
  },

  touchmove() {
    // 空函数 防止滚动
  },

  delete() {
    Dialog.confirm({
      message: '删除后信息将不再展示，且不可恢复！\n 是否确认删除？'
    }).then(() => {
      jobModel.delete(
        {
          id: this.data.id
        },
        (res) => {
          wx.showToast({
            title: '删除成功',
            icon: 'none'
          })
          wx.navigateBack({
            delta: 1
          })
        }
      )
    })
  },

  saveDraft() {
    wx.setStorageSync('recruitData', this.data.PubEmployment)
    wx.showToast({
      title: '草稿保存成功！'
    })
  },

  getDraft() {
    const PubEmployment =
      wx.getStorageSync('recruitData') || this.data.PubEmployment
    this.setData({
      PubEmployment
    })
  },

  removeDraft() {
    wx.removeStorageSync('recruitData')
  },

  init() {
    this.getAgeList()
    this.getExperienceList()
    this.getSalaryList()
    this.getShopTypeList()
    this.getWelfareList()
    this.getPacketSize()
  }
})
